package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.redis.RedisService;
import cn.wolfcode.shop.cloud.util.SeckillKeyPrefix;
import cn.wolfcode.shop.cloud.util.VerifyCodeImgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class VerifyCodeImgController{
    @Autowired
    private RedisService redisService;
    @RequestMapping("/initVerifyCodeImg")
    public Result initVerifyCodeImg(String uuid, HttpServletResponse response) throws IOException {
        //1、生成验证码
        String verifyCode = VerifyCodeImgUtil.generateVerifyCode();
        //2、将验证码的结果获取出来
        Integer calc = VerifyCodeImgUtil.calc(verifyCode);
        //3、将计算出来的验证码结果存入redis中
        redisService.set(SeckillKeyPrefix.SECKILL_VERIFYCODE,uuid,calc+"");
        //4、生成图片,将验证码的表达式放入图片中
        BufferedImage verifyCodeImg = VerifyCodeImgUtil.createVerifyCodeImg(verifyCode);
        //5、将验证码图片响应给浏览器
        ImageIO.write(verifyCodeImg, "JPG",response.getOutputStream());
        return Result.success("");
    }
}
